import sqlobject
import model
import os

options = {
    'db_version': '1',
    'port': '8080',
    'theme': 'oxygen',
}

def build_dir(path):
    dirs = [
        '%s' % path,
        '%s/db' % path,
        '%s/themes' % path,
        '%s/plugins' % path,
    ]
    for dir in dirs:
        os.system('mkdir -p %s' % dir)

def build_cfg(path):
    f = open( path, 'w+')
    for key, val in options.iteritems():
        f.write('%s=%s\n' % (key, val))
    f.close()
    

def build_db(path):
    connect_db(path)
    model.note.createTable()
    model.block.createTable()
    model.tag.createTable()    

def connect_db(path):
    db_url = os.path.abspath(path)
    db_connection_str = 'sqlite:%s' % db_url
    sqlobject.sqlhub.processConnection = \
        sqlobject.connectionForURI(db_connection_str)

def load(path):
    file = open(path)
    lines = file.readlines(100000)
    if not lines:
        return 
    for line in lines:
        line.strip()
        if line.find('=') == -1:
            break
        key, val = line.split('=')
        key.strip()
        val.strip()
        if options.has_key(key):
            options[key] = val
